﻿using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;

namespace FinScreen.Util
{
    static class Extenions
    {
        public static double? ToDouble(this string value)
        {
            double v;
            if (double.TryParse(value.Trim(), out v))
                return v;
            return null;
        }
        public static int? ToInt(this string value)
        {
            int v;
            if (int.TryParse(value.Trim(), out v))
                return v;
            return null;
        }
        public static DateTime? ToDateTime(this string value)
        {
            DateTime v;
            if (DateTime.TryParse(value.Trim(), out v))
                return v;
            return null;
        }
        public static bool Between(this double? value, double min, double max)
        {
            return (value != null && value.Value >= min && value.Value < max);
        }
        public static bool Between(this double value, double min, double max)
        {
            return (value >= min && value < max);
        }


        public static T MergeProperties<T>(this T obj, params object[] vs)
        {
            var resultProperties = obj.GetType().GetProperties();

            resultProperties
                .ToList()
                .ForEach(p =>
                {
                    foreach (var v in vs)
                    {
                        if (v == null) continue;
                        var vProperties = v.GetType().GetProperties();

                        var vProperty = vProperties.FirstOrDefault(p1 => p1.Name == p.Name);
                        if (vProperty != null)
                            p.SetValue(obj, vProperty.GetValue(v));
                    }
                });

            return obj;
        }

        public static BindingList<T> BindingList<T>(this DataGridView view)
        {
            if ((view.DataSource as BindingList<T>) == null) 
                view.DataSource = new BindingList<T>();
            return view.DataSource as BindingList<T>;
        }

        public static void Add<T>(this DataGridView view, T obj)
        {
            view.BindingList<T>().Add(obj);
        }

        public static void Remove<T>(this DataGridView view, T obj)
        {
            view.BindingList<T>().Remove(obj);
        }

        public static void Clear<T>(this DataGridView view)
        {
            view.BindingList<T>().Clear();
        }
    }
}
